package com.nju.graphx

import java.sql.DriverManager
import scala.collection.mutable.ListBuffer

/**
 * JDBCUtil
 * 获取\插入MySQL数据
 *
 * @authorliyunfei
 * @date2022/12/11
 * */
object JdbcUtil {
  val driver = "com.mysql.cj.jdbc.Driver"
  val url = "jdbc:mysql://47.98.99.88:3306/cclab?useUnicode=true&serverTimezone=Asia/Shanghai&characterEncoding=utf8&autoReconnect=true&useSSL=false&allowMultiQueries=true"
  val username = "practice"
  val passwd = "123456"
  /**
   * 加载driver类
   */
  Class.forName(driver)

  /**
   * 获取会话连接
   * @return
   */
  def getConn()={
      DriverManager.getConnection(url, username, passwd)
  }

  /**
   * 查询数据
   * @param sql 查询SQL SELECT * FROM table_name
   * @return
   */
  def query(sql:String)={
      val preparedStatement = getConn().prepareStatement(sql)
      preparedStatement.executeQuery()
  }

  /**
   * 插入数据
   * @param sql 插入SQL INSERT INTO table_name VALUES(?,?)
   * @param args 插入参数
   * @return
   */
  def insert(sql:String,args: ListBuffer[Any])={
      val preparedStatement = getConn().prepareStatement(sql)
      var index = 1
      args.foreach(
          arg=>{
             if(arg.isInstanceOf[String]){
                   preparedStatement.setString(index,arg.toString)
             }
             if(arg.isInstanceOf[Int]){
                   preparedStatement.setInt(index,arg.toString.toInt)
             }
             if (arg.isInstanceOf[Long]) {
                   preparedStatement.setLong(index, arg.toString.toLong)
             }
             index=index+1
          }
      )
      preparedStatement.execute()
  }

}
